<template>
  <PageWrapper>
    <a-card>
      <a-tabs @change="tabsChaneg" v-model:activeKey="activeKey">
        <a-tab-pane key="1" :tab="t('sys.configuration.normal')" />
        <a-tab-pane key="2" :tab="t('sys.configuration.NoNormal')" />
        <a-tab-pane key="3" :tab="t('sys.configuration.Unmarked')" />
        <a-tab-pane key="4" :tab="t('sys.configuration.badness')" />
        <template #rightExtra>
          <div class="flex items-center">
            <a-button @click="DownSubmitTaskClick()" style="margin-right: 10px" type="primary">
              {{ t('sys.informaionMatchaing.columns.AcceptTask') }}
            </a-button>
            <a-button
              @click="DownSubmitClick()"
              style="margin-right: 10px"
              :icon="h(UploadOutlined)"
              type="primary"
            >
              {{ t('sys.configuration.submit') }}
            </a-button>
            <a-button
              @click="DownloadOutClick()"
              style="margin-right: 10px"
              :icon="h(CloudDownloadOutlined)"
              type="primary"
            >
              {{ t('sys.script.download') }}
            </a-button>
            <a-checkbox
              class="mr-2"
              v-model:checked="checkAll"
              :indeterminate="indeterminate"
              @change="onCheckAllChange"
            >
              全选
            </a-checkbox>
          </div>
        </template>
      </a-tabs>
      <a-spin :spinning="loadingMore" tip="Loading...">
        <a-card class="scrollable-card" @scroll="handleScroll">
          <a-checkbox-group
            @change="handleCheckChange"
            v-model:value="expandedRowKeys"
            style="width: 100%"
          >
            <a-row :gutter="[20, 20]">
              <!-- 只渲染可见区域的卡片 -->
              <a-col
                v-for="(item, index) in visibleData"
                :key="item.id"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="6"
                :xl="4"
                :xxl="3"
              >
                <a-card @click="clickItem(item)">
                  <a-image
                    class="lazy-image"
                    :preview="false"
                    width="100%"
                    height="100%"
                    :src="item.avatar"
                    loading="lazy"
                  />
                  <div class="w-full flex justify-between mt-3">
                    <a-select
                      allow-clear
                      v-model:value="item.markingStatus"
                      @click.stop
                      style="min-width: 60px"
                      @change="handleChange(item)"
                      :disabled="!expandedRowKeys.includes(item.id)"
                      :placeholder="t('sys.form.placeholder.status')"
                      option-label-prop="label"
                    >
                      <a-select-option :value="1" :label="t('sys.configuration.normal')">
                        {{ t('sys.configuration.normal') }}
                      </a-select-option>
                      <a-select-option :value="2" :label="t('sys.configuration.NoNormal')">
                        {{ t('sys.configuration.NoNormal') }}
                      </a-select-option>
                      <a-select-option :value="3" :label="t('sys.configuration.Unmarked')">
                        {{ t('sys.configuration.Unmarked') }}
                      </a-select-option>
                      <a-select-option :value="4" :label="t('sys.configuration.badness')">
                        {{ t('sys.configuration.badness') }}
                      </a-select-option>
                    </a-select>
                    <a-checkbox @click.stop :value="item.id" />
                  </div>
                </a-card>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-card>
      </a-spin>
    </a-card>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, reactive, h, computed } from 'vue';
  import { SearchOutlined, UploadOutlined, CloudDownloadOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { useI18n } from '@/hooks/web/useI18n';
  import { getavatarAPI, getavatarstatusAPI, useravatorlist } from '@/api/demo/device';

  const { t } = useI18n();
  const activeKey = ref('1');
  const formState = reactive({});
  const userInfoId = ref<any>(localStorage.getItem('id'));

  // 性能优化：减少每页数量
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 30, // 从50减少到30
  });

  const dataSource = ref<any[]>([]);
  const loadingMore = ref(false);

  // 可见数据计算
  const visibleData = computed(() => {
    return dataSource.value.slice(0, pagination.value.current * pagination.value.pageSize);
  });

  const tabsChaneg = (key) => {
    activeKey.value = key;
    pagination.value.current = 1;
    dataSource.value = [];
    init();
  };

  const handleScroll = (e) => {
    const target = e.target as HTMLElement;
    const scrollBottom = target.scrollHeight - target.scrollTop - target.clientHeight;

    if (scrollBottom < 100 && !loadingMore.value) {
      loadMore();
    }
  };

  const loadMore = async () => {
    if (pagination.value.current * pagination.value.pageSize >= pagination.value.total) {
      return;
    }

    loadingMore.value = true;
    pagination.value.current += 1;

    try {
      const result = (await getavatarAPI({
        size: pagination.value.pageSize,
        current: pagination.value.current,
        uid: userInfoId.value,
        markingStatus: activeKey.value,
      })) as { items: any[]; total: number };

      // 使用 push 方法添加数据
      Array.prototype.push.apply(dataSource.value, result.items);
      pagination.value.total = result.total;
    } catch (error) {
      console.error('加载更多数据时出错:', error);
      pagination.value.current -= 1;
    } finally {
      loadingMore.value = false;
    }
  };

  const checkAll = ref(false);
  const indeterminate = ref(false);
  const expandedRowKeys = ref<number[]>([]);
  const dataavatarStatusList = ref<any[]>([]);

  const onCheckAllChange = (e: any) => {
    expandedRowKeys.value = e.target.checked ? dataSource.value.map((item) => item.id) : [];
    dataavatarStatusList.value = expandedRowKeys.value.map((id) => ({
      id,
      markingStatus: activeKey.value,
    }));
  };

  const handleCheckChange = (e: any[]) => {
    dataavatarStatusList.value = dataSource.value
      .filter((item) => e.includes(item.id))
      .map((item) => ({
        id: item.id,
        markingStatus: item.markingStatus,
      }));
  };

  const handleChange = (item) => {
    const index = dataavatarStatusList.value.findIndex((it) => it.id == item.id);
    if (index !== -1) {
      dataavatarStatusList.value[index].markingStatus = item.markingStatus;
    }
  };

  const clickItem = (item) => {
    const id = item.id;
    const index = expandedRowKeys.value.indexOf(id);

    if (index === -1) {
      expandedRowKeys.value.push(id);
      dataavatarStatusList.value.push({
        id,
        markingStatus: item.markingStatus,
      });
    } else {
      expandedRowKeys.value.splice(index, 1);
      const statusIndex = dataavatarStatusList.value.findIndex((it) => it.id === id);
      if (statusIndex > -1) {
        dataavatarStatusList.value.splice(statusIndex, 1);
      }
    }
  };

  const DownSubmitClick = () => {
    getavatarstatusAPI(dataavatarStatusList.value).then((res) => {
      if (res.code == 200) {
        message.success(t('sys.api.operationSuccess'));
        dataavatarStatusList.value = [];
        expandedRowKeys.value = [];
        checkAll.value = false;
        init();
      }
    });
  };

  const DownloadOutClick = async () => {
    try {
      const response = await fetch('/basic-api/sys/task/user/images-zip', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ markingStatus: activeKey.value }),
      });
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'image.zip';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('下载文件时出错:', error);
    }
  };

  const DownSubmitTaskClick = async () => {
    try {
      const res = await useravatorlist(userInfoId.value);
      if (res.code == 200) {
        message.success(t('sys.api.operationSuccess'));
        dataavatarStatusList.value = [];
        expandedRowKeys.value = [];
        init();
      }
    } catch (error) {
      console.error('下载文件时出错:', error);
    }
  };

  const init = async () => {
    loadingMore.value = true;
    const result = (await getavatarAPI({
      size: pagination.value.pageSize,
      uid: userInfoId.value,
      current: 1,
      markingStatus: activeKey.value,
    })) as { items: any[]; total: number };

    dataSource.value = result.items;
    pagination.value.total = result.total;
    pagination.value.current = 1;

    setTimeout(() => {
      loadingMore.value = false;
    }, 300);
  };

  onMounted(() => {
    init();
  });
</script>

<style scoped lang="scss">
  .scrollable-card {
    height: 85vh;
    overflow-y: auto;
  }

  .lazy-image {
    transition: opacity 0.3s ease;
    background-color: #f5f5f5;
  }

  .lazy-image.loaded {
    opacity: 1;
  }

  :deep(.ant-card-body) {
    padding: 12px 10px 6px;
  }

  .status-indicator {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }

  .dot {
    width: 10px;
    height: 10px;
    margin-right: 8px;
    border-radius: 50%;
  }
</style>
